﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Ymatou.User.Dto.Auth;
using YmtAuth.AppService.Model;
using YmtAuth.Dto;
using YmtSystem.CrossCutting;
using ServiceStack;
namespace YmtAuth.AppService.ThirdPartyService
{
    public class RequestAuthToken
    {
        public string Token { get; set; }
        public string sClientType { get; set; }
        public string DeviceId { get; set; }
        public string TokenSource { get; set; }
        public string ClientIp { get; set; }
    }

    /// <summary>
    /// JAVA版的认证服务
    /// </summary>
    public class UserAuthService
    {
        public const string getUserByTokenUri = "http://auth.iapi.ymatou.com/api/token/auth";

        //public const string getUserBillsUri = "http://auth.iapi.ymatou.com/api/user/find";

        public const string getUserBillsUri = "http://userservice.iapi.ymatou.com/json/reply/UserBillsRequestDto";        


//        private static readonly JsonServiceClient client
//                    = new JsonServiceClient(getUserByTokenUri);
//
//        static UserAuthService()
//        {
//            client.StoreCookies = false;
//            client.Timeout=TimeSpan.FromMilliseconds(500);
//            client.ReadWriteTimeout=TimeSpan.FromMilliseconds(500);
//        }

        /// <summary>
        /// TOKEN登录（调用JAVA的认证服务）
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public static async Task<ResponseData<TokenResponseDto>> GetUserByTokenAsync(SignAuthRequestDto dto)
        {
            try
            {
//                string token = dto.Token;
//
//                string url = string.Format("{0}/?Token={1}&sClientType={2}&DeviceId={3}&TokenSource={4}&ClientIp={5}", getUserByTokenUri
//                , token
//                , dto.sClientType
//                , dto.DeviceId
//                , dto.TokenSource
//                , dto.ClientIp);
//
//                WebClient wc = new WebClient();
//                wc.Encoding = Encoding.UTF8;
//                string resJson = wc.DownloadString(url);
               JsonServiceClient client
                    = new JsonServiceClient(getUserByTokenUri);

      
            client.StoreCookies = false;
            client.Timeout=TimeSpan.FromMilliseconds(1000);
            client.ReadWriteTimeout = TimeSpan.FromMilliseconds(1000);
       
               
               return await client.GetAsync<ResponseData<TokenResponseDto>>(new RequestAuthToken
                {
                    Token = dto.Token,
                    sClientType = dto.sClientType,
                    DeviceId = dto.DeviceId,
                    TokenSource = dto.TokenSource,
                    ClientIp = dto.ClientIp
                }).ConfigureAwait(false);
                //return JsonConvert.DeserializeObject<ResponseData<TokenResponseDto>>(resJson);
            }
            catch(Exception ex)
            {
                YmatouLoggingService.Error(string.Format("[GetUserByToken] java, Token认证出现异常: {0}, token: {1}, RId: {2}", ex.Message, dto.Token, dto.RequestId), ex);
                return ResponseData<TokenResponseDto>.CreateFail(new TokenResponseDto { }, "400", "Token认证出现异常: "+ex.Message);
            }
        }
        public static  ResponseData<TokenResponseDto>GetUserByToken(SignAuthRequestDto dto)
        {
            try
            {
                                string token = dto.Token;
                
                                string url = string.Format("{0}/?Token={1}&sClientType={2}&DeviceId={3}&TokenSource={4}&ClientIp={5}", getUserByTokenUri
                                , token
                                , dto.sClientType
                                , dto.DeviceId
                                , dto.TokenSource
                                , dto.ClientIp);
                
                                WebClient wc = new WebClient();
                                wc.Encoding = Encoding.UTF8;
                                string resJson = wc.DownloadString(url);


              
                return JsonConvert.DeserializeObject<ResponseData<TokenResponseDto>>(resJson);
            }
            catch (Exception ex)
            {
                YmatouLoggingService.Error(string.Format("[GetUserByToken] java, Token认证出现异常: {0}, token: {1}, RId: {2}", ex.Message, dto.Token, dto.RequestId), ex);
                return ResponseData<TokenResponseDto>.CreateFail(new TokenResponseDto { }, "400", "Token认证出现异常: " + ex.Message);
            }
        }
        /// <summary>
        /// 获取用户凭据（调用JAVA的认证服务）
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public static ResponseData<BillsResponseDto> GetUserBills(UserBillsRequestDto dto)
        {
            int userId = dto.UserId;
            string loginId = dto.LoginId;

            try
            {
                string url = string.Format("{0}?UserId={1}&LoginId={2}&Mail={3}&Mobile={4}&LoginPassword={5}", getUserBillsUri
                , userId
                , loginId
                , dto.Mail
                , dto.Mobile
                , dto.LoginPassword);

                WebClient wc = new WebClient();
                wc.Encoding = Encoding.UTF8;
                string resJson = wc.DownloadString(url);
                YmatouLoggingService.Debug("[UserBillsRequest] java, userId: {0}, loginId: {1}, resJson: {2}", userId, loginId, resJson);
                return JsonConvert.DeserializeObject<ResponseData<BillsResponseDto>>(resJson);
            }
            catch (Exception ex)
            {
                YmatouLoggingService.Error(string.Format("[UserBillsRequest] java, userId: {0}, loginId: {1}, error, 获取用户凭据出现异常: {2}", userId, loginId, ex.Message), ex);
                return ResponseData<BillsResponseDto>.CreateFail(new BillsResponseDto { }, "400", "获取用户凭据出现异常: " + ex.Message);
            }
        }
    }
}
